package lovedna.utils;
import lovedna.net.ImageLoader;
import nme.display.Bitmap;
import nme.display.BitmapData;
import nme.installer.Assets;

/**
 * ...
 * @author liwei
 */

class LBitmapCache 
{
	private static var instance:LBitmapCache;
	private var _dict:Hash<Array<Bitmap>>;
	private var _bmdDict:Hash<BitmapData>;
	private var _loader:ImageLoader;
	public function new() {
		if (instance != null) {
			throw "use getInstance";
			return;
		}
		_dict = new Hash<Array<Bitmap>>();
		_bmdDict = new Hash<BitmapData>();
		_loader = new ImageLoader();
		_loader.onComplete = onComplete;
	}
	public static function getInstance():LBitmapCache {
		if (instance == null) {
			instance = new LBitmapCache();
		}
		return instance;
	}
	public function setLoaderCount(value:Int):Void {
		_loader.setMax(value);
	}
	public function getBitmap(url:String, ?bitmap:Bitmap=null,?priority:Int = -1):Bitmap {
		if (bitmap == null) {
			bitmap = new Bitmap();
		}
		var bmd:BitmapData = _bmdDict.get(url);
		if (bmd != null) {
			bitmap.bitmapData = bmd;
		}else {
			var list:Array<Bitmap>;
			if (_dict.exists(url)) {
				list = _dict.get(url);
			}else {
				list = new Array<Bitmap>();
				_dict.set(url, list);
			}
			list.push(bitmap);
			#if cpp
			Reflect.callMethod(this, onComplete, [url,Assets.getBitmapData(url)]);
			#else
			_loader.load(url, priority);
			#end
		}
		return bitmap;
	}
	private function onComplete(url:String, value:BitmapData):Void {
		_bmdDict.set(url, value);
		if (_dict.exists(url)) {
			var list:Array<Bitmap> = _dict.get(url);
			var len:Int = list.length;
			while (len-->0) {
				list.pop().bitmapData = value;
			}
			_dict.remove(url);
		}
	}
	
}